package org.midy.infrastructure.tools;

import java.util.concurrent.atomic.AtomicBoolean;

public class ThreadTools {

    public static void sleepRandom(long baseTimeoutMils) {
        long round = Math.round(Math.random() * 1000);
        long endTime = System.currentTimeMillis() + baseTimeoutMils + round;
        long waitGap = 0L;
        while ( (waitGap = endTime - System.currentTimeMillis()) > 0 )
        {
            try {
                Thread.sleep(waitGap);
            } catch (Throwable t){
                Logger.warn("sleep is notify");
            }
        }
    }

    public static void sleep(long baseTimeoutMils) {
        long endTime = System.currentTimeMillis() + baseTimeoutMils;
        long waitGap = 0L;
        Logger.info("睡眠等待[%d]ms", baseTimeoutMils);
        while ( (waitGap = endTime - System.currentTimeMillis()) > 0 )
        {
            try {
                Thread.sleep(waitGap);
            } catch (Throwable t){
                Logger.warn("sleep is notify");
            }
        }
    }

    public static void hold(AtomicBoolean notify) {
        Thread thread = Thread.currentThread();
        synchronized (notify) {
            while (notify.get()) {
                try {
                    notify.wait();
                } catch (InterruptedException e) {
                    Logger.info("线程挂起等待：%s", e.getMessage());
                }
            }
        }
    }
}
